class DigitalHuman {
    constructor(container) {
        this.container = container;
        this.scene = null;
        this.camera = null;
        this.renderer = null;
        this.human = null;
        this.clock = new THREE.Clock();
        this.isSpeaking = false;
        this.mouthMorphTargets = [];
        this.eyeMorphTargets = [];
        
        this.init();
        this.animate();
    }

    init() {
        console.log('初始化3D数字人...');
        
        // 创建场景
        this.scene = new THREE.Scene();
        this.scene.background = new THREE.Color(0x87CEEB);
        console.log('场景已创建');

        // 创建相机
        this.camera = new THREE.PerspectiveCamera(
            75,
            window.innerWidth / window.innerHeight,
            0.1,
            1000
        );
        this.camera.position.set(0, 0, 5);
        console.log('相机已创建');

        // 创建渲染器
        this.renderer = new THREE.WebGLRenderer({ antialias: true });
        this.renderer.setSize(window.innerWidth, window.innerHeight);
        this.renderer.shadowMap.enabled = true;
        this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
        this.renderer.outputColorSpace = THREE.SRGBColorSpace;
        this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
        this.renderer.toneMappingExposure = 1.2;

        this.container.appendChild(this.renderer.domElement);
        console.log('渲染器已创建并添加到容器');

        // 添加光照
        this.setupLighting();
        console.log('光照已设置');

        // 创建数字人模型
        this.createHuman();
        console.log('数字人模型已创建');

        // 添加环境
        this.createEnvironment();
        console.log('环境已创建');

        // 窗口大小调整
        window.addEventListener('resize', () => this.onWindowResize());
        
        console.log('3D数字人初始化完成');
    }

    setupLighting() {
        // 环境光
        const ambientLight = new THREE.AmbientLight(0x404040, 0.6);
        this.scene.add(ambientLight);

        // 主光源
        const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
        directionalLight.position.set(5, 5, 5);
        directionalLight.castShadow = true;
        directionalLight.shadow.mapSize.width = 2048;
        directionalLight.shadow.mapSize.height = 2048;
        this.scene.add(directionalLight);

        // 补光
        const fillLight = new THREE.DirectionalLight(0xffffff, 0.3);
        fillLight.position.set(-5, 0, -5);
        this.scene.add(fillLight);

        // 点光源（眼睛高光）
        const pointLight = new THREE.PointLight(0xffffff, 0.5, 100);
        pointLight.position.set(0, 2, 3);
        this.scene.add(pointLight);
    }

    createHuman() {
        // 创建数字人组
        this.human = new THREE.Group();

        // 创建头部
        this.createHead();
        
        // 创建身体
        this.createBody();
        
        // 创建头发
        this.createHair();
        
        // 创建眼睛
        this.createEyes();
        
        // 创建嘴巴
        this.createMouth();

        this.scene.add(this.human);
    }

    createHead() {
        // 创建更圆润的头部（动漫风格）
        const headGeometry = new THREE.SphereGeometry(1, 32, 32);
        headGeometry.scale(1, 1.2, 0.8); // 让头部更圆润，稍微拉长
        
        const headMaterial = new THREE.MeshLambertMaterial({ 
            color: 0xFFE4C4, // 更白皙的肤色
            transparent: true,
            opacity: 0.95
        });
        
        const head = new THREE.Mesh(headGeometry, headMaterial);
        head.position.y = 0.5;
        head.castShadow = true;
        head.receiveShadow = true;
        
        this.human.add(head);
        this.head = head;
        
        // 添加腮红
        this.createBlush();
    }

    createBody() {
        // 创建更纤细的身体（动漫少女风格）
        const bodyGeometry = new THREE.CylinderGeometry(0.7, 0.5, 1.8, 16);
        const bodyMaterial = new THREE.MeshLambertMaterial({ 
            color: 0xFFB6C1 // 粉色上衣
        });
        
        const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
        body.position.y = -0.3;
        body.castShadow = true;
        body.receiveShadow = true;
        
        this.human.add(body);
        this.body = body;
        
        // 添加裙子
        this.createSkirt();
    }

    createHair() {
        // 创建动漫风格的双马尾
        const hairGeometry = new THREE.SphereGeometry(1.1, 16, 16, 0, Math.PI * 2, 0, Math.PI * 0.6);
        const hairMaterial = new THREE.MeshLambertMaterial({ 
            color: 0xFF69B4 // 粉色头发
        });
        
        const hair = new THREE.Mesh(hairGeometry, hairMaterial);
        hair.position.y = 0.7;
        hair.rotation.x = Math.PI * 0.1;
        
        this.human.add(hair);
        this.hair = hair;
        
        // 添加双马尾
        this.createTwinTails();
    }

    createEyes() {
        // 创建动漫风格的大眼睛
        // 眼白
        const eyeWhiteGeometry = new THREE.SphereGeometry(0.2, 16, 16);
        const eyeWhiteMaterial = new THREE.MeshLambertMaterial({ color: 0xFFFFFF });
        
        const leftEyeWhite = new THREE.Mesh(eyeWhiteGeometry, eyeWhiteMaterial);
        leftEyeWhite.position.set(-0.35, 0.6, 0.75);
        leftEyeWhite.scale.set(1.5, 1, 0.3); // 让眼睛更大更扁
        
        const rightEyeWhite = leftEyeWhite.clone();
        rightEyeWhite.position.set(0.35, 0.6, 0.75);
        
        this.human.add(leftEyeWhite, rightEyeWhite);
        
        // 瞳孔
        const pupilGeometry = new THREE.SphereGeometry(0.08, 16, 16);
        const pupilMaterial = new THREE.MeshLambertMaterial({ color: 0x000000 });
        
        const leftPupil = new THREE.Mesh(pupilGeometry, pupilMaterial);
        leftPupil.position.set(-0.35, 0.6, 0.85);
        
        const rightPupil = leftPupil.clone();
        rightPupil.position.set(0.35, 0.6, 0.85);
        
        this.human.add(leftPupil, rightPupil);
        this.leftEye = leftPupil;
        this.rightEye = rightPupil;
        
        // 高光
        const highlightGeometry = new THREE.SphereGeometry(0.03, 8, 8);
        const highlightMaterial = new THREE.MeshLambertMaterial({ color: 0xFFFFFF });
        
        const leftHighlight = new THREE.Mesh(highlightGeometry, highlightMaterial);
        leftHighlight.position.set(-0.32, 0.65, 0.9);
        
        const rightHighlight = leftHighlight.clone();
        rightHighlight.position.set(0.38, 0.65, 0.9);
        
        this.human.add(leftHighlight, rightHighlight);
    }

    createMouth() {
        // 创建动漫风格的小嘴
        const mouthGeometry = new THREE.SphereGeometry(0.1, 16, 16, 0, Math.PI * 2, 0, Math.PI * 0.5);
        const mouthMaterial = new THREE.MeshLambertMaterial({ color: 0xFF69B4 }); // 粉色嘴唇
        
        const mouth = new THREE.Mesh(mouthGeometry, mouthMaterial);
        mouth.position.set(0, 0.2, 0.8);
        mouth.rotation.x = Math.PI;
        mouth.scale.set(1.2, 0.8, 0.5); // 让嘴巴更小更可爱
        
        this.human.add(mouth);
        this.mouth = mouth;
    }

    createBlush() {
        // 创建腮红
        const blushGeometry = new THREE.SphereGeometry(0.15, 8, 8);
        const blushMaterial = new THREE.MeshLambertMaterial({ 
            color: 0xFFB6C1,
            transparent: true,
            opacity: 0.6
        });
        
        const leftBlush = new THREE.Mesh(blushGeometry, blushMaterial);
        leftBlush.position.set(-0.6, 0.3, 0.7);
        leftBlush.scale.set(0.8, 0.6, 0.3);
        
        const rightBlush = leftBlush.clone();
        rightBlush.position.set(0.6, 0.3, 0.7);
        
        this.human.add(leftBlush, rightBlush);
    }

    createSkirt() {
        // 创建蓬蓬裙
        const skirtGeometry = new THREE.ConeGeometry(1.2, 1.5, 16);
        const skirtMaterial = new THREE.MeshLambertMaterial({ 
            color: 0xFF1493 // 深粉色裙子
        });
        
        const skirt = new THREE.Mesh(skirtGeometry, skirtMaterial);
        skirt.position.y = -1.2;
        skirt.rotation.x = Math.PI;
        
        this.human.add(skirt);
        this.skirt = skirt;
    }

    createTwinTails() {
        // 创建双马尾
        const tailGeometry = new THREE.CylinderGeometry(0.1, 0.15, 1.5, 8);
        const tailMaterial = new THREE.MeshLambertMaterial({ 
            color: 0xFF69B4
        });
        
        // 左马尾
        const leftTail = new THREE.Mesh(tailGeometry, tailMaterial);
        leftTail.position.set(-0.8, 0.5, 0);
        leftTail.rotation.z = -0.3;
        leftTail.rotation.x = 0.2;
        
        // 右马尾
        const rightTail = new THREE.Mesh(tailGeometry, tailMaterial);
        rightTail.position.set(0.8, 0.5, 0);
        rightTail.rotation.z = 0.3;
        rightTail.rotation.x = 0.2;
        
        this.human.add(leftTail, rightTail);
        this.leftTail = leftTail;
        this.rightTail = rightTail;
    }

    createEnvironment() {
        // 创建梦幻的地面
        const groundGeometry = new THREE.PlaneGeometry(20, 20);
        const groundMaterial = new THREE.MeshLambertMaterial({ 
            color: 0xFFB6C1 // 粉色地面
        });
        
        const ground = new THREE.Mesh(groundGeometry, groundMaterial);
        ground.rotation.x = -Math.PI / 2;
        ground.position.y = -2;
        ground.receiveShadow = true;
        
        this.scene.add(ground);

        // 背景装饰
        this.createBackgroundDecorations();
        
        // 添加樱花效果
        this.createCherryBlossoms();
    }

    createBackgroundDecorations() {
        // 添加一些装饰性的几何体（心形和星星）
        for (let i = 0; i < 15; i++) {
            const geometry = new THREE.SphereGeometry(0.05, 8, 8);
            const material = new THREE.MeshLambertMaterial({ 
                color: new THREE.Color().setHSL(0.8 + Math.random() * 0.2, 0.8, 0.7) // 粉色系
            });
            
            const decoration = new THREE.Mesh(geometry, material);
            decoration.position.set(
                (Math.random() - 0.5) * 20,
                Math.random() * 5,
                (Math.random() - 0.5) * 20
            );
            
            this.scene.add(decoration);
        }
    }

    createCherryBlossoms() {
        // 创建飘落的樱花花瓣
        for (let i = 0; i < 20; i++) {
            const petalGeometry = new THREE.SphereGeometry(0.02, 4, 4);
            const petalMaterial = new THREE.MeshLambertMaterial({ 
                color: 0xFFB6C1,
                transparent: true,
                opacity: 0.8
            });
            
            const petal = new THREE.Mesh(petalGeometry, petalMaterial);
            petal.position.set(
                (Math.random() - 0.5) * 20,
                Math.random() * 10 + 5,
                (Math.random() - 0.5) * 20
            );
            petal.scale.set(2, 0.5, 0.5); // 让花瓣更扁
            
            this.scene.add(petal);
        }
    }

    startSpeaking(duration = 3) {
        this.isSpeaking = true;
        
        // 嘴巴动画
        this.animateMouth(duration);
        
        // 头部轻微摆动
        this.animateHead(duration);
        
        // 眼睛眨眼
        this.animateBlinking(duration);
    }

    stopSpeaking() {
        this.isSpeaking = false;
        
        // 重置嘴巴位置
        if (this.mouth) {
            gsap.to(this.mouth.scale, {
                duration: 0.3,
                y: 1,
                ease: "power2.out"
            });
        }
    }

    animateMouth(duration) {
        if (!this.mouth) return;
        
        const tl = gsap.timeline({ repeat: -1 });
        
        tl.to(this.mouth.scale, {
            duration: 0.1,
            y: 1.5,
            ease: "power2.inOut"
        })
        .to(this.mouth.scale, {
            duration: 0.1,
            y: 1,
            ease: "power2.inOut"
        })
        .to(this.mouth.scale, {
            duration: 0.15,
            y: 1.3,
            ease: "power2.inOut"
        })
        .to(this.mouth.scale, {
            duration: 0.1,
            y: 1,
            ease: "power2.inOut"
        });
        
        // 停止说话时清除动画
        setTimeout(() => {
            tl.kill();
            this.stopSpeaking();
        }, duration * 1000);
    }

    animateHead(duration) {
        if (!this.head) return;
        
        const tl = gsap.timeline({ repeat: -1 });
        
        tl.to(this.head.rotation, {
            duration: 0.5,
            y: 0.1,
            ease: "power2.inOut"
        })
        .to(this.head.rotation, {
            duration: 0.5,
            y: -0.1,
            ease: "power2.inOut"
        });
        
        setTimeout(() => {
            tl.kill();
            gsap.to(this.head.rotation, {
                duration: 0.3,
                y: 0,
                ease: "power2.out"
            });
        }, duration * 1000);
    }

    animateBlinking(duration) {
        if (!this.leftEye || !this.rightEye) return;
        
        const blink = () => {
            gsap.to([this.leftEye.scale, this.rightEye.scale], {
                duration: 0.1,
                y: 0.1,
                ease: "power2.inOut",
                onComplete: () => {
                    gsap.to([this.leftEye.scale, this.rightEye.scale], {
                        duration: 0.1,
                        y: 1,
                        ease: "power2.inOut"
                    });
                }
            });
        };
        
        // 定期眨眼
        const blinkInterval = setInterval(blink, 2000);
        
        setTimeout(() => {
            clearInterval(blinkInterval);
        }, duration * 1000);
    }

    updateControls(rotationSpeed, animationIntensity, expressionIntensity) {
        // 更新旋转速度
        this.rotationSpeed = rotationSpeed;
        
        // 更新动画强度
        this.animationIntensity = animationIntensity;
        
        // 更新表情强度
        this.expressionIntensity = expressionIntensity;
    }

    animate() {
        requestAnimationFrame(() => this.animate());
        
        const elapsedTime = this.clock.getElapsedTime();
        
        // 缓慢旋转
        if (this.human) {
            this.human.rotation.y += (this.rotationSpeed || 1) * 0.005;
        }
        
        // 呼吸动画
        if (this.body) {
            this.body.scale.y = 1 + Math.sin(elapsedTime * 2) * 0.02 * (this.animationIntensity || 1);
        }
        
        // 头发轻微摆动
        if (this.hair) {
            this.hair.rotation.y = Math.sin(elapsedTime * 1.5) * 0.05 * (this.animationIntensity || 1);
        }
        
        // 双马尾摆动
        if (this.leftTail && this.rightTail) {
            this.leftTail.rotation.z = -0.3 + Math.sin(elapsedTime * 2) * 0.1 * (this.animationIntensity || 1);
            this.rightTail.rotation.z = 0.3 + Math.sin(elapsedTime * 2 + Math.PI) * 0.1 * (this.animationIntensity || 1);
        }
        
        this.renderer.render(this.scene, this.camera);
    }

    onWindowResize() {
        this.camera.aspect = window.innerWidth / window.innerHeight;
        this.camera.updateProjectionMatrix();
        this.renderer.setSize(window.innerWidth, window.innerHeight);
    }

    dispose() {
        if (this.renderer) {
            this.renderer.dispose();
        }
        if (this.container && this.renderer) {
            this.container.removeChild(this.renderer.domElement);
        }
    }
}
